<template>
  <PageContainer title="设备地图">
    <div class="device-map">
      <el-row :gutter="20">
        <!-- 左侧树形列表 -->
        <el-col :span="6">
          <el-card>
            <template #header>
              <span>设备列表</span>
            </template>
            <el-tree
              ref="deviceTree"
              :data="deviceTreeData"
              :props="treeProps"
              node-key="id"
              show-checkbox
              default-expand-all
              @check-change="handleCheckChange"
            >
              <template #default="{ node, data }">
                <span class="tree-node">
                  <span>{{ node.label }}</span>
                  <span v-if="data.deviceCount" class="device-count">
                    ({{ data.deviceCount }})
                  </span>
                </span>
              </template>
            </el-tree>
          </el-card>
        </el-col>

        <!-- 右侧地图区域 -->
        <el-col :span="18">
          <el-card>
            <div class="map-container">
              <div id="deviceMap" style="height: 600px; width: 100%;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import PageContainer from '@/components/PageContainer.vue'

// 地图实例
const map = ref<any>(null)
const deviceTree = ref<any>(null)

// 设备树形数据
const deviceTreeData = ref([
  {
    id: 1,
    label: '海恒社区',
    deviceCount: 4,
    children: [
      { id: 101, label: '回收箱-001', lat: 31.7835, lng: 117.2218, status: 'online' },
      { id: 102, label: '回收箱-002', lat: 31.7838, lng: 117.2225, status: 'online' },
      { id: 103, label: '回收箱-003', lat: 31.7842, lng: 117.2231, status: 'online' },
      { id: 104, label: '回收箱-004', lat: 31.7845, lng: 117.2238, status: 'offline' }
    ]
  },
  {
    id: 2,
    label: '莲花社区',
    deviceCount: 3,
    children: [
      { id: 201, label: '回收箱-005', lat: 31.7850, lng: 117.2245, status: 'online' },
      { id: 202, label: '回收箱-006', lat: 31.7853, lng: 117.2252, status: 'online' },
      { id: 203, label: '回收箱-007', lat: 31.7856, lng: 117.2259, status: 'online' }
    ]
  },
  {
    id: 3,
    label: '锦绣社区',
    deviceCount: 3,
    children: [
      { id: 301, label: '回收箱-008', lat: 31.7860, lng: 117.2265, status: 'online' },
      { id: 302, label: '回收箱-009', lat: 31.7863, lng: 117.2272, status: 'offline' },
      { id: 303, label: '回收箱-010', lat: 31.7866, lng: 117.2279, status: 'online' }
    ]
  },
  {
    id: 4,
    label: '临湖社区',
    deviceCount: 2,
    children: [
      { id: 401, label: '回收箱-011', lat: 31.7870, lng: 117.2285, status: 'online' },
      { id: 402, label: '回收箱-012', lat: 31.7873, lng: 117.2292, status: 'online' }
    ]
  }
])

// 树形配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: '046579d7934df85661486783b16904df',
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType']
    })

    // 创建地图实例
    map.value = new AMap.Map('deviceMap', {
      zoom: 14,
      center: [117.225, 31.785],
      viewMode: '3D'
    })

    // 添加控件
    map.value.addControl(new AMap.ToolBar())
    map.value.addControl(new AMap.Scale())
    map.value.addControl(new AMap.HawkEye())
    map.value.addControl(new AMap.MapType())

    // 添加设备标记
    addDeviceMarkers(AMap)
  } catch (error) {
    console.error('地图初始化失败:', error)
  }
}

// 添加设备标记
const addDeviceMarkers = (AMap: any) => {
  if (!map.value) return

  // 清空现有标记
  map.value.clearMap()

  // 添加所有设备标记
  deviceTreeData.value.forEach(area => {
    area.children?.forEach(device => {
      const marker = new AMap.Marker({
        position: [device.lng, device.lat],
        title: device.label,
        content: createMarkerContent(device)
      })

      // 设置设备ID作为扩展数据
      marker.setExtData({ deviceId: device.id })

      // 添加点击事件
      marker.on('click', () => {
        showDeviceInfo(device, AMap)
      })

      map.value.add(marker)
    })
  })
}

// 创建标记内容
const createMarkerContent = (device: any) => {
  const statusColor = device.status === 'online' ? '#67C23A' : '#F56C6C'
  return `
    <div style="
      background: ${statusColor};
      width: 20px;
      height: 20px;
      border-radius: 50%;
      border: 2px solid white;
      box-shadow: 0 2px 6px rgba(0,0,0,0.3);
      cursor: pointer;
    "></div>
  `
}

// 显示设备信息
const showDeviceInfo = (device: any, AMap: any) => {
  // 模拟设备满溢数据（0-100%）
  const fullness = Math.floor(Math.random() * 100)
  const isFull = fullness > 80

  // 模拟清运人员信息
  const cleaners = [
    { name: '张三', phone: '138****1234' },
    { name: '李四', phone: '139****5678' },
    { name: '王五', phone: '136****9012' }
  ]
  const cleaner = cleaners[Math.floor(Math.random() * cleaners.length)]

  const infoWindow = new AMap.InfoWindow({
    content: `
      <div style="padding: 10px; min-width: 280px;">
        <h3 style="margin: 0 0 10px 0; color: #409EFF;">${device.label}</h3>
        <p><strong>状态:</strong> <span style="color: ${device.status === 'online' ? '#67C23A' : '#F56C6C'}">${device.status === 'online' ? '在线' : '离线'}</span></p>
        <p><strong>满溢程度:</strong> <span style="color: ${isFull ? '#F56C6C' : '#67C23A'}">${fullness}% ${isFull ? '(已满溢)' : ''}</span></p>
        <p><strong>清运人员:</strong> ${cleaner.name}</p>
        <p><strong>联系方式:</strong> ${cleaner.phone}</p>
        <p><strong>位置:</strong> 经度 ${device.lng.toFixed(4)}, 纬度 ${device.lat.toFixed(4)}</p>
        <p><strong>所属区域:</strong> ${getAreaName(device.id)}</p>
      </div>
    `,
    offset: new AMap.Pixel(0, -30)
  })

  infoWindow.open(map.value, [device.lng, device.lat])
}

// 获取区域名称
const getAreaName = (deviceId: number) => {
  for (const area of deviceTreeData.value) {
    const device = area.children?.find((d: any) => d.id === deviceId)
    if (device) return area.label
  }
  return '未知区域'
}

// 树形选择变化
const handleCheckChange = (data: any, checked: boolean) => {
  if (data.children) {
    // 区域选择，显示/隐藏该区域所有设备
    const deviceIds = data.children.map((d: any) => d.id)
    toggleDeviceMarkers(deviceIds, checked)
  } else {
    // 单个设备选择
    toggleDeviceMarkers([data.id], checked)
  }
}

// 显示/隐藏设备标记
const toggleDeviceMarkers = (deviceIds: number[], show: boolean) => {
  if (!map.value) return

  // 获取所有标记
  const allMarkers = map.value.getAllOverlays('marker')

  // 遍历所有标记，根据设备ID显示/隐藏
  allMarkers.forEach((marker: any) => {
    const deviceId = marker.getExtData()?.deviceId
    if (deviceId && deviceIds.includes(deviceId)) {
      if (show) {
        marker.show()
      } else {
        marker.hide()
      }
    }
  })
}

onMounted(() => {
  initMap()
})
</script>

<style lang="scss" scoped>
.device-map {
  .map-container {
    margin-bottom: 0;
  }

  .tree-node {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .device-count {
    color: #909399;
    font-size: 12px;
  }
}
</style>
